package com.xunyin.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
public class DeviceUtil1 {
    private final static String APIID = "bl951ab89edebf41b5";
    private final static String APIKEY = "d90a259cff9b9e2563112ccb2ea37d7a";
    private final static String BASE_URL = "https://api.parkline.cc/api";
    private final static String TOKEN_URL = BASE_URL + "/token";
    private final static String DEVICECGI_URL = BASE_URL + "/devicecgi";
    private final static String REFERER = "https://zj.xcxke.com";
    private final static Map<String, DeviceToken> TOKEN_MAP = new HashMap<>();

    public static void main(String[] args) {
//        // 1、客户开门
//        System.out.println(userUnlock("223610", "202407231555", "202407241126"));
        // 1、管理员开门
        System.out.println(adminUnlock("223610"));
        // 1、管理员断电
        System.out.println(adminLock("223610"));
//        getToken();
    }

    /**
     * 获取token
     * @return {"expires_in":"2024-07-23 16:54:44","access_token":"66r/4sNyROC7kAaGXYaLDGFeDq4jdsIkc2f3cbTHsXUVZyegFUBAzyBdZ1LEEIYrvNFh87tpKLU="}
     */
    private static String getToken() {
        String tokenKey = "token";
        DeviceToken deviceToken = TOKEN_MAP.get(tokenKey);
        if (deviceToken != null && deviceToken.getTimeout() > System.currentTimeMillis()) {
            log.info("获取到存量token");
            return deviceToken.getToken();
        }

        HashMap<String, String> hm = new HashMap<>();
        hm.put("apiid", APIID);
        hm.put("apikey", APIKEY);
        String result = null;
        try {
            URL url = new URL(TOKEN_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestProperty("referer", REFERER);
            conn.setRequestMethod("POST");
            PrintWriter pw = new PrintWriter(conn.getOutputStream());
            pw.print(getParams(hm));
            pw.flush();
            pw.close();
            if (conn.getResponseCode() == 200) {
                StringBuffer sb = new StringBuffer();
                String readLine;
                BufferedReader responseReader;
                responseReader = new BufferedReader(new InputStreamReader(conn
                        .getInputStream(), "utf-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine);
                }
                responseReader.close();
                result = sb.toString();
            }
        } catch (Exception ex) {
            log.error("获取token失败", ex);
        }
        log.info("获取token结果:{}", result);
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            String token = jsonObject.getString("access_token");
            deviceToken = new DeviceToken();
            deviceToken.setToken(token);
            deviceToken.setTimeout(System.currentTimeMillis() + 7100000L);
            TOKEN_MAP.put(tokenKey, deviceToken);
            return token;
        } catch (Exception e) {

        }
        return "";
    }

    /**
     * 管理员断电
     * @param devid
     * @return {"devid":"227501","code":"0","msg":"success"}
     */
    public static boolean adminLock(String devid) {
        HashMap<String, String> hm = new HashMap<>();
        hm.put("token", getToken());
        hm.put("devid", devid);
        hm.put("typeid", "04");
        hm.put("lockid", "01");
        String result = null;
        try {
            URL url = new URL(DEVICECGI_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestProperty("referer", REFERER);
            conn.setRequestMethod("POST");
            PrintWriter pw = new PrintWriter(conn.getOutputStream());
            pw.print(getParams(hm));
            pw.flush();
            pw.close();
            if (conn.getResponseCode() == 200) {
                StringBuffer sb = new StringBuffer();
                String readLine;
                BufferedReader responseReader;
                responseReader = new BufferedReader(new InputStreamReader(conn
                        .getInputStream(), "utf-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine);
                }
                responseReader.close();
                result = sb.toString();
            }
        } catch (Exception ex) {
            log.error("管理员断电失败", ex);
        }
        log.info("管理员断电结果:{}", result);
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            return "0".equals(jsonObject.getString("code")) || "1".equals(jsonObject.getString("code"));
        } catch (Exception e) {

        }
        return false;
    }

    /**
     * 管理员开门
     * @param devid
     * @return {"devid":"227501","code":"0","msg":"success"}
     */
    public static boolean adminUnlock(String devid) {
        HashMap<String, String> hm = new HashMap<>();
        hm.put("token", getToken());
        hm.put("devid", devid);
        hm.put("typeid", "01");
        hm.put("lockid", "01");
        String result = null;
        try {
            URL url = new URL(DEVICECGI_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestProperty("referer", REFERER);
            conn.setRequestMethod("POST");
            PrintWriter pw = new PrintWriter(conn.getOutputStream());
            pw.print(getParams(hm));
            pw.flush();
            pw.close();
            if (conn.getResponseCode() == 200) {
                StringBuffer sb = new StringBuffer();
                String readLine;
                BufferedReader responseReader;
                responseReader = new BufferedReader(new InputStreamReader(conn
                        .getInputStream(), "utf-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine);
                }
                responseReader.close();
                result = sb.toString();
            }
        } catch (Exception ex) {
            log.error("管理员开门失败", ex);
        }
        log.info("管理员开门结果:{}", result);
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            return "0".equals(jsonObject.getString("code")) || "1".equals(jsonObject.getString("code"));
        } catch (Exception e) {

        }
        return false;
    }

    /**
     * 客户开门
     * @param devid
     * @param startime 格式：202304271530表示2023年04月27日15时30分
     * @param endtime 格式：202304271530表示2023年04月27日15时30分
     * @return {"devid":"227501","code":"0","msg":"success"}
     */
    public static boolean userUnlock(String devid, Date startime, Date endtime) {
        HashMap<String, String> hm = new HashMap<>();
        hm.put("token", getToken());
        hm.put("devid", devid);
        hm.put("typeid", "01");
        hm.put("lockid", "01");
        hm.put("startime", DateUtil.parseDate2String(startime, "yyyyMMddHHmm"));
        hm.put("endtime", DateUtil.parseDate2String(endtime, "yyyyMMddHHmm"));
        log.info("开门参数={}", JSONObject.toJSONString(hm));
        String result = null;
        try {
            URL url = new URL(DEVICECGI_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestProperty("referer", REFERER);
            conn.setRequestMethod("POST");
            PrintWriter pw = new PrintWriter(conn.getOutputStream());
            pw.print(getParams(hm));
            pw.flush();
            pw.close();
            if (conn.getResponseCode() == 200) {
                StringBuffer sb = new StringBuffer();
                String readLine;
                BufferedReader responseReader;
                responseReader = new BufferedReader(new InputStreamReader(conn
                        .getInputStream(), "utf-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine);
                }
                responseReader.close();
                result = sb.toString();
            }
        } catch (Exception ex) {
            log.error("客户开门失败", ex);
        }
        log.info("客户开门结果:{}", result);
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            return "0".equals(jsonObject.getString("code")) || "1".equals(jsonObject.getString("code"));
        } catch (Exception e) {

        }
        return false;
    }

    /**
     * 客户开门
     * @param devid
     * @param startime 格式：202304271530表示2023年04月27日15时30分
     * @param endtime 格式：202304271530表示2023年04月27日15时30分
     * @return {"devid":"227501","code":"0","msg":"success"}
     */
    public static boolean userUnlock(String devid, String startime, String endtime) {
        HashMap<String, String> hm = new HashMap<>();
        hm.put("token", getToken());
        hm.put("devid", devid);
        hm.put("typeid", "01");
        hm.put("lockid", "01");
        hm.put("startime", startime);
        hm.put("endtime", endtime);
        String result = null;
        try {
            URL url = new URL(DEVICECGI_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestProperty("referer", REFERER);
            conn.setRequestMethod("POST");
            PrintWriter pw = new PrintWriter(conn.getOutputStream());
            pw.print(getParams(hm));
            pw.flush();
            pw.close();
            if (conn.getResponseCode() == 200) {
                StringBuffer sb = new StringBuffer();
                String readLine;
                BufferedReader responseReader;
                responseReader = new BufferedReader(new InputStreamReader(conn
                        .getInputStream(), "utf-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine);
                }
                responseReader.close();
                result = sb.toString();
            }
        } catch (Exception ex) {
            log.error("客户开门失败", ex);
        }
        log.info("客户开门结果:{}", result);
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            return "0".equals(jsonObject.getString("code")) || "1".equals(jsonObject.getString("code"));
        } catch (Exception e) {

        }
        return false;
    }

    // 参数处理方法
    public static String getParams(Map<String, String> paramValues) {
        String params = "";
        String beginLetter = "";
        Set<String> key = paramValues.keySet();
        try {
            for (Iterator it = key.iterator(); it.hasNext(); ) {
                String s = (String) it.next();
                if (params.equals("")) {
                    params += beginLetter + s + "="
                            + URLEncoder.encode(paramValues.get(s), "UTF-8");
                } else {
                    params += "&" + s + "="
                            + URLEncoder.encode(paramValues.get(s), "UTF-8");
                }
            }
        } catch (Exception e) {

        }
        return params;
    }
}
